﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;

namespace MJCOMMEN_CS.Commen_cs
{
   public class WeiXin
    {
       //这个是获取openid的方法，需要传id和密匙，微信的code
       public static string get_openid(string AppID, string AppSecret,string code)
       {
           string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+AppID+"&secret="+AppSecret+"&code=" + code + "&grant_type=authorization_code";
           Web_Request net = new Web_Request(url, "GET");
           string text = net.GetResponseText();
           JObject jobj1 = JObject.Parse(text);
           string openid = jobject(jobj1, "openid");
           net.Dispose();
           return openid;
       }

       public static string jobject(JObject jobj, string key)
       {
           string hh = "";
           if (jobj[key] != null)
           {
               hh = jobj[key].ToString().Trim();
           }
           return hh;
       }
       //这是绑定微信菜单的方法，只需传入微信的id和密匙，还有有相应的txt文件
       public static string bind_menus(string AppID, string AppSecret)
       {
           string token_access = GetAccessToken(AppID, AppSecret);
           FileStream fs1 = new FileStream(System.Web.HttpContext.Current.Server.MapPath(".") + "\\menu.txt", FileMode.Open);
           StreamReader sr = new StreamReader(fs1, Encoding.GetEncoding("GBK"));
           string menu = sr.ReadToEnd();
           sr.Close();
           fs1.Close();
           return GetPage("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + token_access + "", menu);
       }
       //去绑定菜单的执行方法
       public static string GetPage(string posturl, string postData)
       {
           Stream outstream = null;
           Stream instream = null;
           StreamReader sr = null;
           HttpWebResponse response = null;
           HttpWebRequest request = null;
           Encoding encoding = Encoding.UTF8;
           byte[] data = encoding.GetBytes(postData);
           // 准备请求...
           try
           {
               // 设置参数
               request = WebRequest.Create(posturl) as HttpWebRequest;
               CookieContainer cookieContainer = new CookieContainer();
               request.CookieContainer = cookieContainer;
               request.AllowAutoRedirect = true;
               request.Method = "POST";
               request.ContentType = "application/x-www-form-urlencoded";
               request.ContentLength = data.Length;
               outstream = request.GetRequestStream();
               outstream.Write(data, 0, data.Length);
               outstream.Close();
               //发送请求并获取相应回应数据
               response = request.GetResponse() as HttpWebResponse;
               //直到request.GetResponse()程序才开始向目标网页发送Post请求
               instream = response.GetResponseStream();
               sr = new StreamReader(instream, encoding);
               //返回结果网页（html）代码
               string content = sr.ReadToEnd();
               string err = string.Empty;
            
               return content;
           }
           catch (Exception ex)
           {
               string err = ex.Message;
               return string.Empty;
           }
       }
       //绑定菜单栏时需要的token获取
       public static string GetAccessToken(string AppID, string AppSecret)
       {

           //获取微信凭证access_token的接口
           string getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
           string respText = "";
           string accessToken = "";

           string url = string.Format(getAccessTokenUrl, AppID, AppSecret);

           HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
           HttpWebResponse response = (HttpWebResponse)request.GetResponse();

           using (Stream resStream = response.GetResponseStream())
           {
               StreamReader reader = new StreamReader(resStream, Encoding.Default);
               respText = reader.ReadToEnd();
               resStream.Close();
           }
           JavaScriptSerializer Jss = new JavaScriptSerializer();
           Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText);
           //通过键access_token获取值
           accessToken = respDic["access_token"].ToString();
           //     }

           return accessToken;
       }
   
    }
}
